package pimpserver;

import java.io.*;
import java.net.*;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.KeyPair;

class Server
{
	private ServerSocket server;
    private boolean encrypt;
	private int port;
    private Statistics stats;
    private KeyPair keyPair;
    private static final String ALGORITHM = "RSA";
    private static final int KEYSIZE = 1024;

	Server(int port)
	{
        keyPair = null;
        this.port = port;
        encrypt = false;
        server = null;
        stats = new Statistics();
        listen();
	}

    Server(int port, boolean encrypt)
	{
        if(encrypt)
        {
            try
            {
                KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
                keypairGenerator.initialize(KEYSIZE);
                keyPair = keypairGenerator.generateKeyPair();
            }
            catch(NoSuchAlgorithmException e)
            {
                System.out.println("Wrong encryption algorithm. Shutting down(server)...");
                System.exit(-1);
            }
        }
        else
            keyPair = null;
        
        this.port = port;
        this.encrypt = encrypt;
        server = null;
        stats = new Statistics();
        listen();
	}

	public void listen()
	{
		try
		{
			server = new ServerSocket(port);
		}
		catch (IOException e)
		{
			System.out.println("Could not listen on port " + port);
			System.exit(-1);
		}
		while(true)
		{
			System.out.println("Waiting for connection");
			ServerThread w;
			try
			{
				w = new ServerThread(server.accept(),keyPair,stats);
				w.start();
			}
			catch (IOException e)
			{
				System.out.println("ERR: Could not process client");
			}
		}
	}

	public void clean()
	{
		try
		{
            System.out.println("Closing server");
			server.close();
		}
		catch (IOException e)
		{
			System.out.println("Could not close server socket");
			System.exit(-1);
		}
	}
}
